// pages/HomeSeller/HomeSeller.js
// var WxParse = require('../../../wxParse/wxParse.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    category: [],
    mainInfo: {},
    telephone: "",
    path: '',
    title: '',
    info: {},
    infoShow: false,
    // pet_status: false,
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    
    isShow: false,
    //
    store_member: [],
    store_room: [], //直播间列表

    micro_communities: [],
    get_recommend_goods: [],
    commentList: [],
    //门店配送 start +++++++++++++++++++++++
    delivery_note: "", //门店配送说明
    delivery_area: [
      [116.403322, 39.920255]
    ], // 配送范围经纬度
    locations: [116.403322, 39.920255], //门店经纬度
    delivery_status: 0, //是否开启门店配送
    markers_2: [{ // 获取返回结果，放到mks数组中
      latitude: 23.099994,
      longitude: 113.324520,
      iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
      width: 20,
      height: 25,
      callout: {
        padding: '10rpx',
        borderRadius: '5rpx'
      }
    }],
    polygons_2: [{
      points: [],
      fillColor: "#FF88887F",
      strokeColor: "#FFF",
      strokeWidth: 2,
      zIndex: 1
    }],
    delivery: {
      longitude: "113.324520",
      latitude: "23.099994"
    },
    delivery_amount: 0, //门店起送金额
    // end ---------------------------
    // 门店独立余额
    // 1:显示余额模块0:不显示模块
    is_open: 0,
    // 余额名称
    balanceTitle: '',
    // 	会员拥有该门店的余额数量
    member_balance: '',
    // 	1:显示充值按钮0:不显示充值按钮
    show_button: 0,
    // 是否显示二维码
    show_qr_code: false,
    // 门店独立余额 end

    tabList: [],
    menuList: [], //标签的数组集合
    tabName: 10,
    tabIndex: 0,
    isLoading: false, //是否处于请求状态
    fromTravelShop:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene,'scene')
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(',');
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          console.log(chil_arr);
          if (chil_arr[0] == 'store_id') {
            this.setData({
              store_id: chil_arr[1]
            });
          }
          if (chil_arr[0] == 'mid') {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id
      });
    }
    if(options.fromTravelShop){
      this.setData({
        fromTravelShop: 1
      });
    }
    this.getStoreInfo();
    this.getBalance();
    // this.checked_pet()
  },
  toStoreBalance(e) {
    let key = e.currentTarget.dataset.key;
    if (key == 'balance') {
      wx.navigateTo({
        url: '/packageI/independenceBalance/storeBalance/balance_recharge?store_id=' + this.data.store_id,
      });
    } else {
      wx.navigateTo({
        url: '/packageI/independenceBalance/independenceBalance?store_id=' + this.data.store_id,
      });
    }
  },
  copybtn(e) {
    let wechatCode = e.currentTarget.dataset.wechat;
    wx.setClipboardData({
      data: wechatCode ? wechatCode : '',
      success(res) {
        wx.showToast({
          icon: 'none',
          title: '复制成功',
          duration: 1000
        });
      }
    });
  },
  chooseTab(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      tabIndex: e.currentTarget.dataset.index,
      tabName: item.value
    });
    if (this.data.tabIndex == 50) {
      wx.navigateTo({
        url: '/packageD/ActivityDetail/ActivityDetail?id=' + item.id + '&store_id=' + this.data.store_id
      });
    } else if (this.data.tabIndex == '赛车成绩') {
      wx.navigateTo({
        url: '/packageH/turmaroundTime/turmaroundIndex/turmaroundIndex?id=' + this.data.store_id,
      });
    } else if (item.value == 80){
      wx.navigateTo({
        url: '/packageF/storeSign/storeSign/storeSign?id='+this.data.store_id,
      })
      return
    }

    this.getTabsData(); //请求标签数据
  },
  getTabsData() {
    if (!this.data.menuList[this.data.tabIndex].url) {
      // getStoreInfo()方法返回并处理menuList数组
      // 如该标签数据需要请求api获取，让后端返回请求接口的api;
      console.log("menu_list该标签没有返回请求api");
      return;
    }
    if (this.data.menuList[this.data.tabIndex].list.length > 0) {
      this.data.isLoadMore = this.data.menuList[this.data.tabIndex].isLoadMore;
      return;
    }
    let _totalPage = 1;
    let _list = [];
    this.data.isLoading = true;
    let urlStr = app.getNetAddresss(this.data.menuList[this.data.tabIndex].url);
    app._postNetWork({
      url: urlStr,
      data: {
        page: 1,
        store_id: this.data.store_id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (this.data.tabName == 20) {
            _totalPage = res.data.last_page;
            _list = this.setCommunities(res.data.data);
          } else if (this.data.tabName == 40) {
            _list = res.data;
          } else if (res.data?.data) {
            _totalPage = res.data.last_page;
            _list = res.data.data;
          } else {
            console.log("getTabsData()::error", res.data);
          }
          this.data.isLoadMore = true;
          this.data.menuList[this.data.tabIndex].isLoadMore = true;
          this.data.menuList[this.data.tabIndex].total_page = _totalPage;
          if (!this.data.menuList[this.data.tabIndex].total_page) {
            this.data.menuList[this.data.tabIndex].total_page = 0;
          }
          this.setData({
            ['menuList[' + this.data.tabIndex + '].list']: _list
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  setCommunities(_data) {
    let arr = [];
    _data.map(item => {
      arr.push({
        id: item.id,
        title: item.title,
        praise_num: item.praise_num,
        has_one_stick_user: {
          avatar: item.user_avatar,
          nickname: item.user_nickname,
        },
        has_many_image: [{
          url: item.image,
          stick_id: item.id
        }]
      });
    });
    return arr;
  },

  toCard(e) {
    let id = e.currentTarget.dataset.cardid;
    if (id) {
      wx.navigateTo({
        url: '/packageB/member/business_card/BusinessCard/BusinessCard?card_id=' + id +
          '&mark=card'
      });
    }
  },
  gomenphone(e) {
    let mobile = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },
  toGood(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      tabName: 10,
      tabIndex: 0
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData();
    } else {
      console.log('没有更多数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    this._share();
    return {
      title: this.data.title,
      path: this.data.path,
      imageUrl:this.data.imageUrl
    };
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    this._share();
    return {
      title: this.data.title,
      path: this.data.path,
      imageUrl:this.data.imageUrl
    };
  },
  //获取页面主要信息
  getStore(data) {
    this.setData({
      mainInfo: data,
      telephone: data.store_mobile,
      commentList: data.comment
    });
  },
  _share() {
    let uid = wx.getStorageSync('yz_uid');
    let _title = this.data.mainInfo.store_name || '';
    let _link = '/packageC/o2o/HomeSeller/HomeSeller?share_tag=2&mid=' + uid + '&store_id=' + this.data.store_id;
    this.setData({
      title: _title,
      path: _link,
      imageUrl:this.data.mainInfo.store_thumb
    });
  },
  goToAdress() {
    let latitude = this.data.mainInfo.lat;
    let longitude = this.data.mainInfo.lng;
    let store_name = this.data.mainInfo.store_name;
    let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
    wx.openLocation({
      latitude: point.lat,
      longitude: point.lng,
      scale: 18,
      name: store_name
    });
  },
  gophone() {
    let mobile = this.data.mainInfo.store_mobile;
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },
  goToShop() {
    wx.navigateTo({
      url: '/packageC/o2o/o2oStore/o2oStore?store_id=' + this.data.store_id + '&fromHome=1&fromTravelShop='+this.data.fromTravelShop
    });
  },
  goToCrash() {
    wx.navigateTo({
      url: '/packageC/cashier/cashier_pay/cashier_pay?store_id=' + this.data.store_id + '&fromHome=1'
    });
  },
  getStoreInfo() {
    let that = this;
    let urlStr 
    if(this.data.fromTravelShop == 1){
      urlStr = app.getNetAddresss("plugin.travel-agency.frontend.store.get-store-info.get-the-provider");
    } else {
      urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-the-provider");
    }
    
    app._getNetWork({
      url: urlStr,
      data: {
        store_id: this.data.store_id,
        url: ""
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.store_decorate && res.data.store_decorate.datas) {
            // 判断是否门店装修跳转 "/packageG/o2o/HomeSeller/HomeSeller"
            wx.redirectTo({
              url: '/packageG/o2o/HomeSeller/HomeSeller?store_id=' + that.data.store_id
            });
            return;
          }
          that.getStore(res.data.store_info);
          that.setTabsList(res.data.menu_list);
          that.setData({
            isShow: true,
            get_recommend_goods: res.data.get_recommend_goods
          });

          if (!app._isTextEmpty(res.data.store_information)) {
            res.data.store_information = res.data.store_information.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block"');
            that.setData({
              info: res.data.store_information,
              infoShow: true
            });
          }

          // 门店配送 start ++++++++++++++++++++++++++++
          if (that.data.mainInfo.store_delivery && that.data.mainInfo.store_delivery.delivery_status == 1) {
            that.setData({
              delivery_status: 1,
              delivery_note: that.data.mainInfo.store_delivery ? that.data.mainInfo.store_delivery.delivery_note : '',
              delivery_amount: that.data.mainInfo.store_delivery ? that.data.mainInfo.store_delivery.delivery_amount : 0,
            });
            let delivery_area = that.data.mainInfo.store_delivery ? that.data.mainInfo.store_delivery.delivery_area : [];
            let locations = that.data.mainInfo.store_delivery ? that.data.mainInfo.store_delivery.locations : [];
            let arr_delivery_area = [];
            if(delivery_area.length >0){
              delivery_area.forEach((item, index) => {
                arr_delivery_area.push([Number(item.R), Number(item.Q)]);
              });
            }
            that.setData({
              delivery_area: arr_delivery_area,
              locations: [Number(locations.longitude).toFixed(6), Number(locations.latitude).toFixed(6)]
            });
            if (that.data.locations && that.data.locations.length > 0) {
              that.setData({
                "markers_2[0].longitude": that.data.locations[0],
                "markers_2[0].latitude": that.data.locations[1],
                "delivery.longitude": that.data.locations[0],
                "delivery.latitude": that.data.locations[1],
              });
            }
            if (that.data.delivery_area && that.data.delivery_area.length > 0) {
              let points = [];
              for (let i = 0; i < that.data.delivery_area.length; i++) {
                points.push({
                  longitude: that.data.delivery_area[i][0],
                  latitude: that.data.delivery_area[i][1]
                });
              }
              that.setData({
                "polygons_2[0].points": points,
              });
            }
          }
          // end ----------------------------
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  setTabsList(_data){
    console.log(_data,'---------------_data')
    let tabList = [];
    let menuList = [];
    // 处理并重新组装新数组和请求api
    _data.forEach((val, index) => {
      if (val.is_show) {
        tabList.push(val);
        menuList.push({
          isLoadMore: true,
          page: 1,
          total_page: 0,
          list: [],
          url: val.api
        });
      }
    });
    this.setData({tabList,menuList});
  },
  // checked_pet() {
  // 	if (wx.getStorageSync('is_open_pet') == 1) {
  // 		this.setData({
  // 			pet_status: true
  // 		})
  // 	}
  // },
  //直播间跳转
  gopage(e) {
    let status = e.currentTarget.dataset.status;
    let id = e.currentTarget.dataset.id;
    let backid = e.currentTarget.dataset.backid;
    if (status == 1) {
      wx.navigateTo({
        url: '/packageD/directSeeding/livePage/livePage?id=' + id + '&playerType=live'
      });
    } else if (status == 2) {
      wx.navigateTo({
        url: '/packageD/directSeeding/livePage/livePage?id=' + id + '&playerType=video' + '&backid=' + backid
      });
    } else if (status == 3) {
      wx.navigateTo({
        url: '/packageD/directSeeding/foreshow/foreshow?id=' + id
      });
    }
  },

  _getMoreData() {
    let that = this;
    this.data.menuList[this.data.tabIndex].isLoadMore = false;
    this.data.isLoadMore = false; // 防止多次请求分页数据

    if (this.data.menuList[this.data.tabIndex].page >= this.data.menuList[this.data.tabIndex].total_page) {
      return;
    } else {
      let _list = [];
      let _json = { store_id: this.data.store_id };
      this.data.menuList[this.data.tabIndex].page = this.data.menuList[this.data.tabIndex].page + 1;
      _json.page = this.data.menuList[this.data.tabIndex].page;
      let urlStr = app.getNetAddresss(this.data.menuList[this.data.tabIndex].url);
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: _json,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            that.data.isLoadMore = true;

            if (this.tabName == 20) {
              _list = this.setCommunities(res.data);
            } else if (this.tabName == 40) {
              _list = res;
            } else if (res&&res.data) {
              _list = res.data;
            } else {
              console.log("getTabsData()::error", res);
            }
            this.setData({
              ['menuList[' + this.data.tabIndex + '].list']: this.data.menuList[this.data.tabIndex].list.concat(_list)
            });
          } else {
            this.data.menuList[this.data.tabIndex].page = this.data.menuList[this.data.tabIndex].page - 1;
            this.data.menuList[this.data.tabIndex].isLoadMore = false;
            this.data.isLoadMore = false;
            return;
          }
        },
        fail: function (res) {
          console.log(res.msg);
        }
      });
    }
  },
  // 门店独立余额
  goToCode() {
    wx.navigateTo({
      url: '/packageC/cashier/cashier_qr/cashier_qr?name=storeBalance&store_id=' + this.data.store_id,
    });
  },
  getBalance() {
    let urlStr
    if(this.data.fromTravelShop == 1){
      urlStr = app.getNetAddresss("plugin.travel-agency.frontend.store.balance.setting.index");
    }else{
      urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.balance.setting.index");
    }
    
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: this.data.store_id,
      },
      success: (resdata) => {
        console.log(resdata);
        let res = resdata.data;
        this.setData({
          is_open: res.data.is_open,
          balanceTitle: res.data.title,
          member_balance: res.data.member_balance,
          show_button: res.data.show_button,
          show_qr_code: res.data.show_qr_code,
        });
      },
      fail: function (res) {
        wx.showToast({
          title: res.data.msg,
          duration: 1000,
          icon: 'none'
        });
      }
    });
  }
  // yuyue() {
  // 	if (wx.getStorageSync('pet_status') == 1) {
  // 		wx.navigateTo({
  // 			url: '/packageA/member/editmobile/editmobile',
  // 		})
  // 	}
  // 	if (wx.getStorageSync('pet_status') == 3) {
  // 		wx.navigateTo({
  // 			url: '/packageC/hospital/memberinfo/memberinfo',
  // 		})
  // 	}
  // 	if (wx.getStorageSync('pet_status') == 4) {
  // 		wx.navigateTo({
  // 			url: '/packageC/hospital/preorder/preorder',
  // 		})
  // 	}
  // }
});